package com.ayf.payment.game.api.utils;

import com.ayf.payment.game.api.bean.BaseResData;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.util.StringTokenizer;

public final class FtpUtil {
    
    static final String fileSeparator = File.separator;

    private static final String XY_HOST = System.getenv("XY_FTP_HOST");
    private static final int XY_PORT = Integer.parseInt(System.getenv("XY_FTP_PORT"));
    private static final String XY_USERNAME = System.getenv("XY_FTP_USERNAME");
    private static final String XY_PASSWORD = System.getenv("XY_FTP_PASSWORD");
    private static final String XY_REMOTE_PATH = System.getenv("XY_FTP_PATH");

//    private static final String XY_HOST = "101.200.139.59";
//    private static final int XY_PORT =21;
//    private static final String XY_USERNAME ="test";
//    private static final String XY_PASSWORD ="ftp@2020";
//    private static final String XY_REMOTE_PATH ="/img";

    private FtpUtil() {}

    /**
     * ftp文件上传
     *
     * @param bytes    文件内容字节数组
     * @param fileName 文件名称
     * @param path     如果path为空，默认值设置为REMOTE_PATH
     */
    public static BaseResData uploadXYFile(byte[] bytes, String fileName, String path, String traceId) {
        BaseResData baseResData = new BaseResData();
        if (StringUtils.isBlank(path)) {
            path = XY_REMOTE_PATH;
        }
        LogPortal.info("fileName:{},path:{} 开始上传",fileName,path);
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {
            ftpClient.connect(XY_HOST, XY_PORT);
            ftpClient.login(XY_USERNAME, XY_PASSWORD);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                //判断目录是否存在,不存在,则创建
                boolean dirExist = ftpClient.changeWorkingDirectory(path);
                if (!dirExist) {
                    StringTokenizer s = new StringTokenizer(path, fileSeparator);
                    s.countTokens();
                    String pathName = "";
                    while (s.hasMoreElements()) {
                        pathName = pathName + fileSeparator +s.nextElement();
                        try {
                            ftpClient.makeDirectory(pathName);
                        } catch (Exception e) {
                            LogPortal.error("{} {} {} ftp makeDirectory异常",e,traceId,fileName,pathName);
                            break;
                        }
                    }
                    ftpClient.changeWorkingDirectory(path);
                }
                ftpClient.storeFile(fileName, new ByteArrayInputStream(bytes));
                ftpClient.logout();
                baseResData.setSuccess(true);
                baseResData.setData(path.concat(fileName));
                LogPortal.info("{}fileName:{} 上传完成",traceId,fileName);
            }
        } catch (IOException e) {
            LogPortal.error("{}:{} FTP上传异常",e,traceId,fileName);
            throw new RuntimeException(e.getMessage(),e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
            }
        }
        return baseResData;
    }

    /**
     * ftp文件下载
     *
     * @param dir      目录
     * @param fileName 要下载的文件名
     * @return
     */
    public static byte[] downloadXYFile(String dir, String fileName) {
        FTPClient ftpClient = new FTPClient();
        ByteArrayOutputStream os = null;
        try {
            int reply;
            ftpClient.connect(XY_HOST, XY_PORT);
            ftpClient.login(XY_USERNAME, XY_PASSWORD);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            }
            if (StringUtils.isBlank(dir)) {
                dir = XY_REMOTE_PATH;
            }
            LogPortal.info("fileName:{},path:{} 开始下载",fileName,dir);
            ftpClient.changeWorkingDirectory(dir);//转移到FTP服务器目录
            os = new ByteArrayOutputStream();
            ftpClient.retrieveFile(new String(fileName.getBytes("GBK"), "ISO-8859-1"), os);
            ftpClient.logout();
            byte [] returnByte = os.toByteArray();
            LogPortal.info("fileName:{},path:{} 下载完成 {}字节",fileName,dir,returnByte.length);
            return returnByte;
        } catch (IOException e) {
            LogPortal.error("{} FTP下载异常",e,fileName);
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(os);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {}
            }
        }
    }

    /**
     * ftp文件上传
     *
     * @param file
     * @param path 如果path为空，默认值设置为REMOTE_PATH
     */
    public static void uploadXYFile(File file, String path) {
        if (StringUtils.isBlank(path)) {
            path = XY_REMOTE_PATH;
        }
        String fileName = file.getName();
        LogPortal.info("fileName:{},path:{} 开始上传",fileName,path);
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            ftpClient.connect(XY_HOST, XY_PORT);
            ftpClient.login(XY_USERNAME, XY_PASSWORD);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                //判断目录是否存在,不存在,则创建
                boolean dirExist = ftpClient.changeWorkingDirectory(path);
                if (!dirExist) {
                    StringTokenizer s = new StringTokenizer(path,fileSeparator);
                    s.countTokens();
                    String pathName = "";
                    while (s.hasMoreElements()) {
                        pathName = pathName + fileSeparator +s.nextElement();
                        try {
                            ftpClient.makeDirectory(pathName);
                        } catch (Exception e) {
                            break;
                        }
                    }
                    ftpClient.changeWorkingDirectory(path);
                }
                ftpClient.storeFile(file.getName(), inputStream);
                ftpClient.logout();
                LogPortal.info("fileName:{} 上传完成",fileName);
            }
        } catch (IOException e) {
            LogPortal.error("{} {} FTP上传异常",e,path,file.getName());
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {}
        }
    }

    public static void main(String[] args) {
       // File file = new File("E:/FTP/FTP1/842002649527291904.jpg");
      //  uploadXYFile(file, "");

        FileOutputStream fStream = null;
        BufferedOutputStream stream = null;
        try {
            byte[] bytes = downloadXYFile("", "842002649527291904.jpg");
            String str=Base64.encode(bytes);
            File file2 = new File("/Users/syf/Desktop/112.jpg");
            if(!file2.exists()){
                file2.createNewFile();
            }
            fStream = new FileOutputStream(file2);
            stream = new BufferedOutputStream(fStream);
            stream.write(bytes);
        } catch (FileNotFoundException e) {
            LogPortal.error("异常信息是:",e);;
        } catch (IOException e) {
            LogPortal.error("异常信息是:",e);;
        }finally {
            try {
                if (stream != null) {
                    stream.close();
                }
                if (null != fStream) {
                    fStream.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
